package com.regis.controller;

import com.regis.entity.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 计算机系 ITAEM 纱雾休比我老婆
 * @Description 文件上传和下载
 * @date 2022/7/29 13:42
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    //注意：file的名字需与前端保持一致
    public ResultVo<String> upload(MultipartFile file) {
        //file是个临时文件，需转存，否则请求结束后文件自动删除
        //获取项目路径
        String rootPath = System.getProperty("user.dir");
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //新文件名
        String fileName = UUID.randomUUID().toString() + suffix;

        //创建目录对象
        File saveFile = new File(rootPath, "src\\images\\" + fileName);
        //判断当前目录是否存在
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        //将临时文件存到指定位置
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResultVo.success(fileName);
    }

    /**
     * 文件下载
     *
     * @param name 文件名称
     * @param response
     */
    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response) {
        //获取文件路径
        String rootPath = System.getProperty("user.dir");
        File file = new File(rootPath, "/src/images/" + name);
        try {
            //输入流，读取文件内容
            FileInputStream fileInputStream = new FileInputStream(file);
            //输出流，发送文件
            ServletOutputStream outputStream = response.getOutputStream();

            //设置响应类型
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
